package cn.edu.tit.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 添加用户
 * @author liangyi
 * @version
 */
public class AddUser {
    public static void main(String[] args) {
		//这个对象scanner用来接收键盘上输入的数据
    	Scanner scanner = new Scanner(System.in);
		System.out.println("请输入用户编号：");
		String userid = scanner.next();//从键盘上接受一个字符串，这里是用户编号
		
		System.out.println("请输入用户名：");
		String username = scanner.next();
		
		System.out.println("请输入密码：");
		String userpsw = scanner.next();
		
		try {
			//接下来的工作是对数据库进行操作，把数据写入数据库表users中
			//1.注册数据库驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2.打开数据库连接
			String url = "jdbc:mysql://localhost:3306/titdb";//titdb是数据库名
			Connection connection = DriverManager.getConnection(url,"root","root");
			//3.准备SQL语句
			String sql = "INSERT INTO users VALUES(?,?,?)";
			PreparedStatement pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, userid);
			pstmt.setString(2, username);
			pstmt.setString(3, userpsw);
			//4.执行SQL语句
			int flag = pstmt.executeUpdate();
			if (flag == 0) {
				System.out.println("添加失败！！！");
			} else {
				System.out.println("OK....");
			}
			//5.关闭连接
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
